<template>
    <div class="home_div">
        <!-- <div class="map-title">
            <h3>JSAPI Vue3地图组件示例</h3>
            <div v-if="back" id="back" @click="showAllMap" style="cursor: pointer;">返回</div>
        </div> -->
        <div id="container"></div>
    </div>
</template>
<script lang="ts">
import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef } from "@vue/reactivity";
import { ref, onMounted, reactive } from "vue";
import { qingyunMapData } from '@/utils/qingyuntest'
export default {
    name: "mapComtaint",
    setup() {
        const map = shallowRef(null) as any;
        const AMap = shallowRef(null) as any;
        const back = ref(false);
        const polygons = shallowRef([]) as any; // 区描边、遮罩
        const district = shallowRef(null) as any;
        const polygon = shallowRef(null) as any; // 市描边、遮罩
        const markers = shallowRef([]) as any; // 自定义标记点
        return {
            map,
            AMap,
            back,
            polygons,
            district,
            polygon,
            markers,
        };
    },
    create() { },
    methods: {
        /*  
        返回区域对应颜色
        adcode:厦门市	        350200
                厦门市市辖区	350201
                思明区	        350203
                海沧区	        350205
                湖里区	        350206
                集美区	        350211
                同安区	        350212
                翔安区	        350213
                */
        getColorByAdcode(adcode: string) {
            let colors = {
                "350200": "#111111",
                "350201": "#456aed",
                "350203": "428cced",
                "350205": "#a456e1",
                "350206": "#123fee",
                "350211": "#666eee",
                "350212": "#963qde",
                "350213": "#784eda",
            } as any;
            return colors[adcode];
        },
        getDataList() {
            let list: any = [[]]
            qingyunMapData.features[0].geometry.coordinates[0].forEach((item: any) => {
                // console.log(item);
                list[0].push(new this.AMap.LngLat(item[0], item[1]))
            })
            return list
        },
        // 初始化遮罩
        initArea(city: string, isChildDraw: boolean = false) {
            let that = this;
            // this.district.search(city, function (status: string, result: any) {
                // 外多边形坐标数组和内多边形坐标数组
                var outer = [
                    new that.AMap.LngLat(-360, 90, true),
                    new that.AMap.LngLat(-360, -90, true),
                    new that.AMap.LngLat(360, -90, true),
                    new that.AMap.LngLat(360, 90, true),
                ];
                // console.log(result);

                // 绘制遮罩
                var holes = that.getDataList();
                console.log(holes);

                var pathArray = [outer];
                pathArray.push.apply(pathArray, holes);
                that.polygon = new that.AMap.Polygon({
                    pathL: pathArray,
                    strokeColor: "#00eeff",
                    strokeWeight: 1,
                    fillColor: "#020933",
                    fillOpacity: 1,
                });
                that.polygon.setPath(pathArray);
                that.map.add(that.polygon);

                // 点击事件
                that.polygon.on('click', (e: any) => {
                    console.log(e);
                })
                // 判断是否要绘制子区域
                // if (isChildDraw) {
                //     // 将搜索层级设置为 区、县
                //     that.district.setLevel("district");
                //     for (let i = 0; i < result.districtList[0].districtList.length; i++) {
                //         that.areaPolyline(result.districtList[0].districtList[i].adcode);
                //     }
                // }
            // });
        },
        // 添加自定义标记点
        addCustomMarkers() {
            // 清除已有标记点
            if (this.markers.length) {
                this.map.remove(this.markers);
                this.markers = [];
            }
            
            // 定义四个点位的坐标和信息
            const markerData = [
                {
                    position: [117.400507, 37.847724], // 点位1坐标
                    title: '点位1',
                    content: '这是第一个标记点'
                },
                {
                    position: [117.440507, 37.807724], // 点位2坐标
                    title: '点位2',
                    content: '这是第二个标记点'
                },
                {
                    position: [117.380507, 37.817724], // 点位3坐标
                    title: '点位3',
                    content: '这是第三个标记点'
                },
                {
                    position: [117.460507, 37.837724], // 点位4坐标
                    title: '点位4',
                    content: '这是第四个标记点'
                }
            ];
            
            // 创建自定义图标
            const customIcon = new this.AMap.Icon({
                size: new this.AMap.Size(32, 32), // 图标大小
                image: 'data:image/svg+xml;base64,' + btoa(`
                    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
                        <circle cx="16" cy="16" r="12" fill="#FF6600" stroke="#fff" stroke-width="2"/>
                        <circle cx="16" cy="16" r="6" fill="#fff"/>
                    </svg>
                `), // 自定义SVG图标
                imageSize: new this.AMap.Size(32, 32)
            });
            
            // 创建标记点
            markerData.forEach((data, index) => {
                const marker = new this.AMap.Marker({
                    position: data.position,
                    icon: customIcon,
                    title: data.title,
                    offset: new this.AMap.Pixel(-16, -16) // 图标偏移量
                });
                
                // 添加点击事件
                marker.on('click', () => {
                    const infoWindow = new this.AMap.InfoWindow({
                        content: `<div style="padding: 10px;"><h4>${data.title}</h4><p>${data.content}</p></div>`,
                        offset: new this.AMap.Pixel(0, -30)
                    });
                    infoWindow.open(this.map, data.position);
                });
                
                this.markers.push(marker);
            });
            
            // 添加到地图
            this.map.add(this.markers);
        },
        // 显示总览
        showAllMap() {
            this.back = false;
            if (this.polygon) {
                // 清除遮罩
                this.map.remove(this.polygon);
            }
            // this.initArea("渤海路街道", true);
            // this.map.setCenter([118.113994, 24.614998]);
            this.map.setCenter([117.383037, 37.786794]);

            this.map.setZoom(11);
            // 重新添加标记点
            this.addCustomMarkers();
        },
        // 绘制区域描边
        areaPolyline(adcode: string) {
            let that = this;
            if (this.polygons.length) {
                this.map.remove(this.polygons);
                this.polygons = [];
            }
            this.district.search(adcode, function (status: string, result: any) {
                console.log("区", result);
                //   绘制区域描边
                let bounds = result.districtList[0].boundaries;
                for (let i = 0; i < bounds.length; i++) {
                    const color = that.getColorByAdcode(result.districtList[0].adcode);
                    const polygon = new that.AMap.Polygon({
                        path: bounds[i],
                        strokeColor: "#784eda",
                        strokeWeight: 4,
                        fillColor: "#784eda",
                        fillOpacity: 0,
                    });
                    // 添加监听事件
                    // polygon.on("mouseover", () => {
                    //     if (!that.back) {
                    //         polygon.setOptions({
                    //             fillOpacity: 0.7,
                    //         });
                    //     }
                    // });
                    // 添加点击事件
                    polygon.on("click", () => {
                        console.log('点击了', result.districtList[0].adcode);


                        // 判断是否为市级
                        // if (!that.back) {
                            // 显示返回按钮
                            that.map.setZoom(12);
                            // 修改中心位置为区级中心
                            that.map.setCenter([
                                result.districtList[0].center.lng,
                                result.districtList[0].center.lat,
                            ]);
                            //   绘画
                            that.initArea(result.districtList[0].adcode, false);
                        // }
                    });
                    polygon.on("mouseout", () => {
                        polygon.setOptions({
                            fillOpacity: 0,
                        });
                    });
                    that.polygons.push(polygon);
                }
                that.map.add(that.polygons);
            });
        },
        ininMap() {
            let that = this;
            // 这个配置很重要，必须设置，否则你的 行政服务搜索api无法使用生成回调
            window._AMapSecurityConfig = {
                securityJsCode: "587b22815e6cc6b14effaa607c627fb7",
            };
            AMapLoader.load({
                key: "e6072f86d2d66d78671eaa4542006354", //设置您的key
                version: "2.0",
                plugins: [
                    "AMap.ToolBar",
                    "AMap.Driving",
                    "AMap.Polygon",
                    "AMap.DistrictSearch",
                    "AMap.Object3DLayer",
                    "AMap.Object3D",
                    "AMap.Polyline",
                    "AMap.Marker",
                    "AMap.InfoWindow",
                    "AMap.Icon"
                ],
                AMapUI: {
                    version: "1.1",
                    plugins: [],
                },
                Loca: {
                    version: "2.0.0",
                },
            })
                .then((AMap) => {
                    that.AMap = AMap;
                    that.map = new AMap.Map("container", {
                        viewMode: "3D",
                        zoom: 13,
                        zooms: [10, 20],
                        center: [117.383037, 37.786794],
                    });
                    that.district = new AMap.DistrictSearch({
                        subdistrict: 3, //获取边界返回下级行政区
                        extensions: "all", //返回行政区边界坐标组等具体信息
                        // level: "city", //查询行政级别为 市
                        level: "district", //查询行政级别为 市

                    });
                    console.log('district===============================',that.district)

                    that.initArea("渤海路街道", true);
                    // 添加自定义标记点
                    that.addCustomMarkers();

                    // 点击事件
                    that.map.on('click', (e: any) => {
                        console.log(e);
                    })


                })
                .catch((e) => {
                    console.log(e);
                });
        },
    },
    mounted() {
        //DOM初始化完成进行地图初始化
        this.ininMap();
    },
};
</script>
<style scope>
.home_div {
    height: 100%;
    width: 100%;
    padding: 0px;
    margin: 0px;
    position: relative;
}

#container {
    height: 100%;
    width: 100%;
    padding: 0px;
    margin: 0px;
}

.map-title {
    position: absolute;
    z-index: 1;
    width: 100%;
    height: 50px;
    background-color: rgba(27, 25, 27, 0.884);
    display: flex;
    justify-content: space-around;
    align-items: center;
}

h3 {
    z-index: 2;
    color: white;
}
</style>